package io.tim.mvc.action;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import io.tim.mvc.util.MVC_Config_Process;
import io.tim.mvc.util.XmlBean;

/**
 * 实现监听器的类，用于提前解析 mvc-config.xml，并将解析出来的 ActionForm、Action 以及跳转 url 等信息存储在上下文中
 * 
 * @author Zhang Nan
 * @since 2017/02/21
 *
 */
@WebListener
public class ActionListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("信息：系统已注销...............................................");

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		
		ServletContext context = arg0.getServletContext();
		// mvc-config 为定义在 web.xml 中的 context-param
		String xmlPath = context.getInitParameter("mvc-config");
		String tomcatPath = context.getRealPath("\\");
		
		// 将获取到的 mvc-config.xml 文件的全路径传给解析程序，并得到解析后的结果
		try {
			Map<String, XmlBean> map = MVC_Config_Process.process(tomcatPath + xmlPath);
			context.setAttribute("mvc-config", map);
			// 打印获得的解析结果
			/*
			Set<String> keySet = map.keySet();
			for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
				String key = it.next();
				System.out.println("path: " + key + ", XmlBean: " + map.get(key));
			}
			*/
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("信息：系统已启动...............................................");
	}

}
